import React, { useCallback } from 'react';
import {
  LogoutOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Avatar, Menu } from 'antd';
import { history, useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { MenuInfo } from 'rc-menu/lib/interface';

const AvatarDropdown: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { currentAccount } = initialState!;

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      // 退出登录
      if (key === 'logout') {
        setInitialState(undefined);
        history.push('/');
        return;
      }
      // 账户信息页面
      history.push(`/account/${key}`);
    },
    [initialState],
  );

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="editAccount">
        <SettingOutlined />
        个人设置
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );

  if (!currentAccount) {
    return <div />;
  }

  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          className={styles.avatar}
          src={currentAccount?.avatar || ''}
          alt="avatar"
          icon={<UserOutlined />}
        />
        <span className={`${styles.name} anticon`}>
          {currentAccount?.username || currentAccount?.address}
        </span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
